package com.ruoyi.app.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.app.common.SmsUtil;
import com.ruoyi.app.common.jwt.SysLoginService;
import com.ruoyi.app.common.jwt.TokenService;
import com.ruoyi.app.service.UserService;
import com.ruoyi.common.ClientUtils;
import com.ruoyi.common.WxValueConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.app.*;
import com.ruoyi.system.mapper.CommunityMemberMapper;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.mapper.app.CardMapper;
import com.ruoyi.system.mapper.app.DeptWxInfoMapper;
import com.ruoyi.system.mapper.app.RechargeOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisCache redisCache;
    @Autowired
    SysLoginService loginService;
    @Autowired
    SmsUtil smsUtil;
    @Autowired
    TokenService tokenService;
    @Autowired
    CardMapper cardMapper;
    @Autowired
    CommunityMemberMapper communityMemberMapper;
    @Autowired
    RechargeOrderMapper rechargeOrderMapper;
    @Autowired
    WxValueConfig wxPledgeConfig;
    @Autowired
    DeptWxInfoMapper deptWxInfoMapper;

    @Override
    public AjaxResult wxLogin(String code, String encrypted, String iv,String name ,String icon,String appId) {
        DeptWxInfo deptWxInfo = deptWxInfoMapper.selectByAppId(appId);
        String path = wxPledgeConfig.getPHONE_URL()
                +"appid="
                + deptWxInfo.getAppId()
                + "&secret="
                + deptWxInfo.getAppSecret()
                + "&js_code="
                + code
                + "&grant_type=authorization_code";
        try {
            // 向微信服务器发送get请求获取加密了的内容
            JSONObject jsonObject = ClientUtils.doGetMethod(path);
            String sessionkey = jsonObject.getString("session_key");
            // 解密
            byte[] encrypData = Base64Utils.decodeFromString(encrypted);
            byte[] ivData = Base64Utils.decodeFromString(iv);
            byte[] sessionKey = Base64Utils.decodeFromString(sessionkey);
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            String resultString = new String(cipher.doFinal(encrypData), "UTF-8");
            JSONObject object = JSONObject.parseObject(resultString);
            // 拿到手机号码
            String phone = object.getString("phoneNumber");
            String openId = jsonObject.getString("openid");
            log.info(object.toJSONString());
            //查询是否为新用户
            User user = userMapper.selectUserByUserPhone(phone,appId);
            if (org.springframework.util.StringUtils.isEmpty(user)) {
                User newUser = new User();
                newUser.setPhone(phone);
                newUser.setNickName(name);
                newUser.setIcon(icon);
                newUser.setState(1);
                newUser.setOpenid(openId);
                newUser.setAppId(appId);
                newUser.setCreateTime(new Date());

                userMapper.insertSelective(newUser);
                log.info("新用户：{}，微信一键登录",phone);
                return AjaxResult.success(loginService.login(newUser.getPhone(),"",appId));
            }else {
                if (user.getState() == 0) {
                    return AjaxResult.error("用户已禁用!");
                }
                log.info("用户登陆:{},微信一键登录",user.getPhone());
                return AjaxResult.success(loginService.login(user.getPhone(),"",appId));
            }
        } catch (Exception e) {
            log.error("微信小程序手机号码解密异常，信息如下:", e);
        }
        return null;
    }

    @Override
    public String smsLogin(String phone, String code,String appId) {

        String redisCode = redisCache.getCacheObject("register:phone" + phone);
        if (StringUtils.isEmpty(redisCode) || !code.equals(redisCode)) {
            throw new ServiceException("验证码错误");
        }
        User user = userMapper.selectUserByUserPhone(phone,appId);
        if (StringUtils.isNull(user)) {
            User newUser = new User();
            newUser.setPhone(phone);
            newUser.setState(1);
            newUser.setNickName("");
            newUser.setCreateTime(new Date());
            newUser.setAppId(appId);
            userMapper.insertSelective(newUser);
            return loginService.login(newUser.getPhone(),"",appId);
        }else {
            if (user.getState() == 0) {
                throw new ServiceException("用户已禁用!");
            }
            return loginService.login(user.getPhone(),"",appId);
        }
    }

    @Override
    public void setPhone(String phone, String code) {
        String redisCode = redisCache.getCacheObject("register:phone" + phone);
        if (StringUtils.isEmpty(redisCode) || !code.equals(redisCode)) {
            throw new ServiceException("验证码错误");
        }
        User user = userMapper.selectByPrimaryKey(tokenService.getUser(ServletUtils.getRequest()).getId());
        User check = userMapper.selectUserByUserPhone(phone,user.getAppId());
        if (StringUtils.isNotNull(check)) {
            throw new ServiceException("手机号已注册！");
        }

        user.setPhone(phone);
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public AjaxResult sendSms(String phone) {
        return smsUtil.sendSms(phone);
    }

    @Override
    public void setUser(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public User getUserInfo() {
        User user = userMapper.selectByPrimaryKey(tokenService.getUser(ServletUtils.getRequest()).getId());
        return user;
    }

    @Override
    public List<Card> cardList() {
        return cardMapper.UserCardList(tokenService.getUser(ServletUtils.getRequest()).getId());
    }

    @Override
    public List<CommunityMember> balanceList(Long communityId) {
        return communityMemberMapper.balanceList(tokenService.getUser(ServletUtils.getRequest()).getId(),communityId);
    }

    @Override
    public void lossCard(Long cardId) {
        Card card = cardMapper.selectByPrimaryKey(cardId);
        if (StringUtils.isNull(card)) {
            throw new ServiceException("电卡不存在");
        }
            card.setCardState(2);
            cardMapper.updateByPrimaryKeySelective(card);
    }

    @Override
    public void unbindCard(Long cardId) {
        cardMapper.unbindCard(cardId);
    }

    @Override
    public void bindCard(String cardNum) {
        Card card = cardMapper.selectByNum(cardNum);
        if (StringUtils.isNull(card)) {
            throw new ServiceException("卡号不存在！");
        }


        if(card.getUserId()!=null || card.getUserName()!=null || card.getOperatorName()==null || card.getCommunityName()==null ){
            throw new ServiceException("绑定卡号错误！");
        }
        User user = userMapper.selectByPrimaryKey(tokenService.getUser(ServletUtils.getRequest()).getId());
        cardMapper.bindCard(card.getId(),user.getId(),user.getNickName());
    }

    @Override
    public RechargeOrder getRechargeStatus() {
        return rechargeOrderMapper.selectByOrderCharge(tokenService.getUser(ServletUtils.getRequest()).getId());
    }
}
